package com.yc.web.controller;

import com.yc.utils.QRCodeUtil;
import com.yc.web.controller.model.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/debug")
@Slf4j
public class DebugController {

    @Value("${app.domain:http://localhost:5173}")
    private String appDomain;
    
    @Value("${app.backend.domain:http://localhost:8088}")
    private String backendDomain;

    /**
     * 测试二维码生成
     */
    @GetMapping("/test-qr")
    public ResponseResult testQRCode(@RequestParam(defaultValue = "test") String text) {
        try {
            // 生成测试链接
            String testUrl = appDomain + "/share/result/test123";
            
            log.info("测试生成二维码，内容: {}", testUrl);
            
            // 生成二维码
            InputStream qrStream = QRCodeUtil.generateQRCodeWithText(testUrl, "测试二维码");
            
            Map<String, Object> result = new HashMap<>();
            result.put("url", testUrl);
            result.put("domain", appDomain);
            result.put("success", qrStream != null);
            result.put("message", "二维码生成成功，内容为: " + testUrl);
            
            return ResponseResult.ok("测试成功").setData(result);
            
        } catch (Exception e) {
            log.error("测试二维码生成失败", e);
            return ResponseResult.error("测试失败: " + e.getMessage());
        }
    }

    /**
     * 直接输出二维码图片（用于验证二维码内容）
     */
    @GetMapping("/qr-image")
    public void getQRImage(@RequestParam(defaultValue = "test") String content, 
                          HttpServletResponse response) {
        try {
            String testUrl = appDomain + "/share/result/" + content;
            
            log.info("生成二维码图片，内容: {}", testUrl);
            
            InputStream qrStream = QRCodeUtil.generateQRCodeWithText(testUrl, "心理测评结果");
            
            response.setContentType("image/png");
            response.setHeader("Content-Disposition", "inline; filename=test-qr.png");
            
            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = qrStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            
            qrStream.close();
            outputStream.close();
            
        } catch (Exception e) {
            log.error("生成二维码图片失败", e);
            response.setStatus(500);
        }
    }

    /**
     * 测试分享token生成和解析
     */
    @GetMapping("/test-token")
    public ResponseResult testToken(@RequestParam(defaultValue = "1") Long recordId,
                                   @RequestParam(defaultValue = "1") Long userId) {
        try {
            // 生成token
            String data = recordId + ":" + userId + ":" + (System.currentTimeMillis() + 30L * 24 * 60 * 60 * 1000);
            String shareToken = Base64.getEncoder().encodeToString(data.getBytes());
            
            // 生成分享链接
            String shareUrl = appDomain + "/share/result/" + shareToken;
            
            // 解析token
            String decodedData = new String(Base64.getDecoder().decode(shareToken));
            String[] parts = decodedData.split(":");
            
            Map<String, Object> result = new HashMap<>();
            result.put("recordId", recordId);
            result.put("userId", userId);
            result.put("shareToken", shareToken);
            result.put("shareUrl", shareUrl);
            result.put("tokenData", decodedData);
            result.put("tokenParts", parts);
            result.put("domain", appDomain);
            
            return ResponseResult.ok("Token测试成功").setData(result);
            
        } catch (Exception e) {
            log.error("Token测试失败", e);
            return ResponseResult.error("Token测试失败: " + e.getMessage());
        }
    }

    /**
     * 检查域名配置
     */
    @GetMapping("/check-domain")
    public ResponseResult checkDomain() {
        Map<String, Object> config = new HashMap<>();
        config.put("frontendDomain", appDomain);
        config.put("backendDomain", backendDomain);
        config.put("serverInfo", "Spring Boot running on port 8088");
        config.put("timestamp", LocalDateTime.now());
        
        return ResponseResult.ok("域名配置检查完成").setData(config);
    }

    /**
     * 测试完整分享流程
     */
    @GetMapping("/test-share-flow")
    public ResponseResult testShareFlow() {
        Map<String, Object> result = new HashMap<>();
        
        // 模拟生成分享token
        String shareToken = "dGVzdDoxOjE3MzQ3ODg4MDA=";  // 测试token
        
        // 生成各种URL
        String frontendShareUrl = appDomain + "/share/" + shareToken;
        String backendApiUrl = backendDomain + "/api/test/share/result/" + shareToken;
        
        result.put("shareToken", shareToken);
        result.put("frontendShareUrl", frontendShareUrl);
        result.put("backendApiUrl", backendApiUrl);
        result.put("qrCodeContent", frontendShareUrl);
        result.put("description", "用户扫码后访问frontendShareUrl，前端页面调用backendApiUrl获取数据");
        
        return ResponseResult.ok("分享流程测试").setData(result);
    }
} 